/*
 * @Author: 徐建辰
 * @Date: 2022-02-15 15:29:19
 * @LastEditTime: 2022-02-16 15:05:40
 * @LastEditors: 徐建辰
 * @Description: 订单模块hook
 */
import {ref, onMounted, computed} from 'vue'
import {Toast, Dialog} from 'vant'
import useAddress from '@/hooks/useAddress'
import {setItem, getItem} from '@/utils/local'
import {CART_ITEM_IDS} from '@/utils/constant'
import {antiShake} from '@/utils/utils'
import {createOrder, getDetailById, payOrder, cancelOrder} from '@/service/order'
import {getByCartItemIds} from '@/service/shopcart'
import {getAddressDetail, getDefaultAddress} from '@/service/address'

export default function useOrder(route) {
  const cartlist = ref([])
  const addressInfo = ref({})
  const detail = ref({})
  const visible = ref(false)
  const orderNo = ref('')

  const {defaultAddress} = useAddress('', '', true)

  onMounted(() => {
    const {id = ''} = route.query
    !id && initCreateOrder()
    id && getOrderDetail(id)
  })

  // 初始化订单
  async function initCreateOrder() {
    const {addressId, cartItemIds} = route.query
    const _cartItemIds = cartItemIds ? JSON.parse(cartItemIds) : JSON.parse(getItem(CART_ITEM_IDS))
    setItem(CART_ITEM_IDS, JSON.stringify(_cartItemIds))
    const {data: list} = await getByCartItemIds({cartItemIds: _cartItemIds.join(',')})
    const {data: address} = addressId ? await getAddressDetail(addressId) : await getDefaultAddress()
    if (!address) {
      Toast('你还没有地址哦')
      router.push({path: '/address'})
      return
    }
    cartlist.value = list
    addressInfo.value = address
    Toast.clear()
  }
  // 生成订单
  function onCreateOrder() {
    const params = {
      addressId: addressInfo.value.addressId,
      cartItemIds: cartlist.value.map(item => item.cartItemId)
    }
    Toast.loading('订单生成中...')
    antiShake(async () => {
      const {data} = await createOrder(params)
      setItem(CART_ITEM_IDS, '')
      Toast.clear()
      orderNo.value = data
      visible.value = true
    })
  }
  // 获取订单详情
  async function getOrderDetail(id) {
    Toast.loading({
      message: '获取数据中',
      forbidClick: true
    })
    const {data} = await getDetailById(id)
    detail.value = data
    Toast.clear()
  }
  // 支付订单
  function handlePayOrder(orderNo, payType, isInit) {
    Toast.loading('支付中...')
    antiShake(async () => {
      const {resultCode, message} = await payOrder({orderNo, payType})
      resultCode !== 200 && Toast.fail(message)
      resultCode === 200 && Toast.success('支付成功')
      Toast.clear()
      isInit && getOrderDetail(route.query.id)
    })
  }
  // 取消订单
  function handleCancelOrder() {
    const orderId = route.query.id
    Dialog.confirm({
      title: '确定要取消这个订单吗？'
    }).then(async () => {
      const {resultCode, message} = await cancelOrder(orderId)
      if (resultCode === 200) {
        Toast.success('取消成功')
        getOrderDetail(orderId)
        return
      }
      Toast.fail(message)
    })
  }
  // 计算总价
  const total = computed(() => {
    let sum = 0
    cartlist.value.forEach(item => {
      sum += item.goodsCount * item.sellingPrice
    })
    return sum
  })

  return {
    cartlist, addressInfo, visible, orderNo, total, detail,
    onCreateOrder, handlePayOrder, handleCancelOrder
  }
}